# -*- coding: utf-8 -*-
import xlrd
import logging
import sys
import re
import requests

reload(sys)
sys.setdefaultencoding('utf8')

logging.basicConfig(
    level=logging.WARN,
    format='%(asctime)s  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    filename='login.log',
    filemode='a')

console = logging.StreamHandler()
console.setLevel(logging.WARN)
formatter = logging.Formatter('%(asctime)s  %(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)

header = {
    "Referer": "https://razerid.razer.com/",
    'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) Gecko/20100101 Firefox/60.0",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "X-Requested-With": "XMLHttpRequest"
}

login = xlrd.open_workbook(r'login.xls')
sheet0 = login.sheet_by_index(0)
rows = sheet0.nrows


def login(email, password):
    success = '登录失败'

    session = requests.session()

    data = {
        "email": email,
        "password": password,
        "serviceCode": '0060'
    }

    response = session.post("https://razerid.razer.com/ajax/login", data=data, headers=header)
    result = response.text
    if result.__contains__('Success'):
        success = '登录成功'

        cookie = response.cookies.get_dict()
        response = session.get("https://razerid.razer.com/account/notification-settings", cookies=cookie)

        pattern = re.compile(ur"accessToken: '(.*?)',")
        m = pattern.search(response.text)
        if m:
            token = m.group(1)
            data = {
                "accessToken": token,
                "body":	'{"apps":[{"app_name":"rzrstore","check":1},{"app_name":"gamestore","check":1},{"app_name":"zvault","check":0},{"app_name":"cortex","check":1},{"app_name":"rzrpmk","check":0}]}'
            }

            response = session.post("https://razerid.razer.com/ajax/newsletter-internal-set", data=data, headers=header)

            result = response.text

            if result.__contains__('Success'):
                success = '勾选成功'

    logging.warn('帐号 '+email+'   结果 '+success)


def main():
    try:
        for i in range(rows):
            login(sheet0.row_values(i)[0], sheet0.row_values(i)[1])
    except BaseException as e:
        print e.message
    finally:
        requests.session().close()


if __name__ == '__main__':
    main()
